package com.lianboke.link.ad.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lianboke.link.ad.R;
import com.lianboke.link.ad.VolleyUtils.HttpCallBack;
import com.lianboke.link.ad.VolleyUtils.HttpUtil;
import com.lianboke.link.ad.app.MyApplication;
import com.lianboke.link.ad.beans.OrdetTypeDetailsBean;
import com.lianboke.link.ad.beans.ResponseReportdevicetaskModel;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.updateUtils.AppUtils;
import com.lianboke.link.ad.updateUtils.DownloadAppManager;
import com.lianboke.link.ad.utils.DeviceUtils;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.MediaUtils;
import com.lianboke.link.ad.utils.ToastUtil;
import com.lianboke.link.ad.utils.imageloader.GlideLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 互助任务详情
 */
public class OrderTypeDetailsForHuZhuActivity extends BaseActivity {

    @BindView(R.id.tv_order_type_title_flag)
    public TextView tv_order_type_title_flag;//名称
    @BindView(R.id.tv_order_type_title_content)
    public TextView tv_order_type_title_content;

    @BindView(R.id.tv_order_type_img_flag)
    public TextView tv_order_type_img_flag;//图标
    @BindView(R.id.iv_order_type_img_content)
    public ImageView iv_order_type_img_content;

    @BindView(R.id.tv_order_type_des_flag)
    public TextView tv_order_type_des_flag;//应用说明
    @BindView(R.id.tv_order_type_des_content)
    public TextView tv_order_type_des_content;

    @BindView(R.id.tv_order_type_manual_flag)
    public TextView tv_order_type_manual_flag;//任务手册
    @BindView(R.id.tv_order_type_manual_content)
    public TextView tv_order_type_manual_content;

    @BindView(R.id.tv_order_type_price_flag)
    public TextView tv_order_type_price_flag;//费用
    @BindView(R.id.tv_order_type_price_content)
    public TextView tv_order_type_price_content;

    @BindView(R.id.tv_order_type_jiaocheng_flag)
    public TextView tv_order_type_jiaocheng_flag;//教程
    @BindView(R.id.tv_order_type_jiaocheng_content)
    public TextView tv_order_type_jiaocheng_content;

    @BindView(R.id.tv_order_type_appstatus_flag)
    public TextView tv_order_type_appstatus_flag;//状态
    @BindView(R.id.tv_order_type_appstatus_content)
    public TextView tv_order_type_appstatus_content;

    @BindView(R.id.loading_progress)
    public ProgressBar loading_progress;

    @BindView(R.id.view_empty)
    public View view_empty;
    @BindView(R.id.view_scrollView)
    public ScrollView view_scrollView;

    @BindView(R.id.btn_join_task)
    public Button btn_join_task;

    public OrdetTypeDetailsBean ordetTypeDetailsBean;//任务详情信息
    private String strOrderId;//任务id
    private String strOrderType;//任务类型
    private String strAppPackageName;//应用的app

    private boolean isHasInstallApp = false;//是否已经安装了此app

    private int iTypeSubmit = -1;//0:认领任务； 1:启动任务

    //可取消的观察者
    private Disposable mDisposable;//可以取消观察者
    @Override
    public int getContentViewId() {
        return R.layout.activity_order_type_details_for_hu_zhu;
    }

    @Override
    public boolean initLocalBroadcastReceiver() {
        return true;
    }

    @Override
    public void initActivityParams(Bundle savedInstanceState) {
        setTitleBackShow(true);
        setTitleContent("互助任务详情");
        strOrderId = getIntent().getStringExtra("order_id");
        strOrderType = getIntent().getStringExtra("order_type");
        //点击查看视频教程
        tv_order_type_jiaocheng_content.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(ordetTypeDetailsBean.getStudyurl())){
                    MediaUtils.openBrowser(actContext,ordetTypeDetailsBean.getStudyurl());
                }else{
                    ToastUtil.show(actContext,"地址错误请联系客服...", Toast.LENGTH_LONG);
                }
            }
        });
        //认领任务
        btn_join_task.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(iTypeSubmit==0) {
                    //认领任务
                    joinOrderTypeInfo();
                }else if(iTypeSubmit==1){
                    //启动任务
                    if(AppUtils.hasApp(actContext,strAppPackageName)){
                        //已安装
                        isHasInstallApp = true;
                        //更新启动时间
                        reportedAppInfo(3,strAppPackageName);
                      //跳转到互粉页面
                        Intent mIntent = new Intent();
                        mIntent.setClass(actContext,OrderTypeDetailsForHuZhuByFansActivity.class);
                        mIntent.putExtra("order_id",ordetTypeDetailsBean.getId());
                        mIntent.putExtra("order_name",ordetTypeDetailsBean.getName());
                        startActivity(mIntent);
                        finish();
                    }else{
                        //未安装
                        isHasInstallApp = false;
                        downloadInstallAppInfo(ordetTypeDetailsBean.getAppdownload());
                    }

                }
            }
        });
        DownloadAppManager.initDownLoadManager(actContext);
        showLoadingProgress();
        getOrderTypeHuZhuDetails();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        closedCustomerLoadingDialog();
        DownloadAppManager.initDownLoadManager(actContext).destoryDownLoadService();
        if(mDisposable!=null && !mDisposable.isDisposed()){
            mDisposable.dispose();
        }
    }
    /**
     * 显示加载进度
     */
    private void showLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!= View.VISIBLE){
            loading_progress.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏加载进度
     */
    private void hideLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!=View.GONE){
            loading_progress.setVisibility(View.GONE);
        }
    }
    /**
     * 获取任务详情
     */
    public void getOrderTypeHuZhuDetails(){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("deviceid", DeviceUtils.getImei(appContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city", MyApplication.strCity);
        params.put("taskid",strOrderId);
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_TYPE_ORDER_DESTORYS, params, new HttpCallBack<OrdetTypeDetailsBean>() {
            @Override
            public void onSuccess(OrdetTypeDetailsBean data) {
                hideLoadingProgress();
                if(data!=null){
                    iTypeSubmit = 0;
                    ordetTypeDetailsBean = data;
                    strAppPackageName = ordetTypeDetailsBean.getAppname();
                    strOrderType = String.valueOf(ordetTypeDetailsBean.getType());
                    showOrderTypeDetails();
                    view_scrollView.setVisibility(View.VISIBLE);
                    view_empty.setVisibility(View.GONE);
                }else{
                    view_scrollView.setVisibility(View.GONE);
                    view_empty.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFail(String msg) {
                hideLoadingProgress();
                view_scrollView.setVisibility(View.GONE);
                view_empty.setVisibility(View.VISIBLE);
                ToastUtil.showShort(actContext,msg);
            }
        });
    }

    /**
     * 显示订单详情
     */
    private void showOrderTypeDetails(){
        tv_order_type_title_content.setText(ordetTypeDetailsBean.getName());
        GlideLoader.loadImage(ordetTypeDetailsBean.getImg(),iv_order_type_img_content);
        tv_order_type_des_content.setText(ordetTypeDetailsBean.getDesc());
        tv_order_type_manual_content.setText(ordetTypeDetailsBean.getMemo());
        tv_order_type_manual_content.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
        tv_order_type_price_content.setText(String.valueOf(ordetTypeDetailsBean.getPrice()));
        //设置下划线
        tv_order_type_jiaocheng_content.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
        if(TextUtils.isEmpty(ordetTypeDetailsBean.getStudyurl())){
            tv_order_type_jiaocheng_content.setText("无视频教程");
            tv_order_type_jiaocheng_content.setClickable(false);
        }else{
            tv_order_type_jiaocheng_content.setText("点击查看");
            tv_order_type_jiaocheng_content.setClickable(true);
        }
        //判断应用是否已安装
        if(AppUtils.hasApp(actContext,strAppPackageName)){
            //已经安装相应的app
            tv_order_type_appstatus_content.setText("已安装此任务");
            isHasInstallApp = true;
        }else {
            tv_order_type_appstatus_content.setText("未安装此任务");
            isHasInstallApp = false;
        }
    }
    /**
     * 认领任务
     */
    public void joinOrderTypeInfo(){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("deviceid", DeviceUtils.getImei(appContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city", MyApplication.strCity);
        params.put("taskid",strOrderId);
        params.put("appname",strAppPackageName);
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_TYPE_ORDER_JOIN, params, new HttpCallBack<ResponseReportdevicetaskModel>() {

            @Override
            public void onSuccess(ResponseReportdevicetaskModel data) {
                //领取任务成功
                if(data!=null && data.getStatus()==1){
                    ToastUtil.showShort(actContext,"任务认领成功!");
                    checkoutOrderFlow();
                }else if(data!=null && !TextUtils.isEmpty(data.getTip())) {
                    ToastUtil.show(appContext,data.getTip(),Toast.LENGTH_SHORT);
                }else {
                    ToastUtil.show(appContext,"此任务认领失败，请稍后再试",Toast.LENGTH_SHORT);
                }
            }
            @Override
            public void onFail(String msg) {
                ToastUtil.showShort(actContext,msg);
            }
        });
    }

    /**
     * 任务认领后检测任务流程
     */
    public void  checkoutOrderFlow(){
        if(isHasInstallApp ){
            //已缓存+已安装,直接启动app
            btn_join_task.setText("启动app");
            iTypeSubmit = 1;
        }else if(!isHasInstallApp){
            //未安装
            downloadInstallAppInfo(ordetTypeDetailsBean.getAppdownload());
        }
    }
    /**
     * 下载与安装app
     */
    public void downloadInstallAppInfo(String strUrl){
        if(TextUtils.isEmpty(strUrl)){
            ToastUtil.show(actContext,"下载地址错误",Toast.LENGTH_SHORT);
        }else{
            initCustomerLoadingDialog("任务下载中...");
            List<String> datas = new ArrayList<String>();
            datas.add(strUrl);
            MyApplication.appPackNameUrlMap.put(ordetTypeDetailsBean.getAppname(),ordetTypeDetailsBean.getAppdownload());
            DownloadAppManager.initDownLoadManager(actContext).startDownLoadApp(datas);
        }
    }

    /**
     * 上报任务状态 1 安装、2 卸载、3 启动、4 完成
     * @param status
     * @param packagename (卸载时需要传卸载的packname)
     */
    public void  reportedAppInfo(int status,String packagename){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("deviceid", DeviceUtils.getImei(appContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city", MyApplication.strCity);

        if(!strAppPackageName.equals(packagename)){
            params.put("taskid","");
            params.put("appname",packagename);
        }else{
            params.put("taskid",strOrderId);
            params.put("appname",strAppPackageName);
        }

        params.put("status",String.valueOf(status));
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_TYPE_ORDER_REPORTPROCESS, params, new HttpCallBack<Integer>() {

            @Override
            public void onSuccess(Integer data) {
                if(data!=null && data.intValue()==1){
                    KLog.e("shangbao_log","-------------onSuccess-------------------");
                }
            }

            @Override
            public void onFail(String msg) {
                KLog.e("shangbao_log","-------------onFail-------------------"+msg);
            }
        });
    }

    //===============================接收器======================================

    /**
     * 接受下载的操作
     * @param action
     */
    @Override
    public void getDownLoadMyBroadcastReceiver(String action) {
        KLog.e("-------------getDownLoadMyBroadcastReceiver----------:"+action);
        if(TextUtils.isEmpty(action)){
            return;
        }
        if("android.myapp.download.downloadstart".equals(action)){
            //开始下载指定app
            Long downloadId = MyApplication.appUrlDownIdMap.get(ordetTypeDetailsBean.getAppdownload());
            if(downloadId>0){
                setShowAndHideCustomLoadingProgress(true);
                startCheckProgress(downloadId);
            }else{
                setShowAndHideCustomLoadingProgress(false);
            }
        }else if("android.myapp.download.downloadsuccess".equals(action)){
            //下载成功
            setShowAndHideCustomLoadingProgress(false);
            updateCustomerLoadingDialog("安装中...");
            setShowAndHideCustomLoadingProgress(false);
        }else if("android.myapp.download.downloadfails".equals(action) || "android.myapp.download.downloadexecption".equals(action)){
            //下载失败
            MyApplication.appPackNameUrlMap.remove(ordetTypeDetailsBean.getAppname());
            closedCustomerLoadingDialog();
            ToastUtil.show(actContext,"任务下载失败，请稍后再试",Toast.LENGTH_SHORT);
        }
    }

    @Override
    public void getInstallMyBroadcastReceiver(String action) {
        //安装
        KLog.e("-------------install----------:"+action);
        if(!TextUtils.isEmpty(action) && strAppPackageName.equals(action) ){
            //关闭等待框
            closedCustomerLoadingDialog();
            //上报状态
            reportedAppInfo(1,strAppPackageName);
            //更新ui
            tv_order_type_appstatus_content.setText("已安装此任务");
            isHasInstallApp = true;
            btn_join_task.setText("启动任务");
            iTypeSubmit = 1;
        }
    }

    @Override
    public void getRemoveMyBroadcastReceiver(String data) {
        //卸载
        KLog.e("-------------remove----------:"+data);
        if(!TextUtils.isEmpty(data) && strAppPackageName.equals(data) ){
            tv_order_type_appstatus_content.setText("未安装此任务");
            isHasInstallApp = false;
            iTypeSubmit = 0;
            reportedAppInfo(2,strAppPackageName);
            //开始下载并安装app
            downloadInstallAppInfo(ordetTypeDetailsBean.getAppdownload());
        }else if(!TextUtils.isEmpty(data)){
            reportedAppInfo(2,data);
        }
    }

    @Override
    public void getReplaceMyBroadcastReceiver(String action) {
        //安装
        KLog.e("-------------install----------:"+action);
        if(!TextUtils.isEmpty(action) && strAppPackageName.equals(action) ){
            //关闭等待框
            closedCustomerLoadingDialog();
            //上报状态
            reportedAppInfo(1,strAppPackageName);
            //更新ui
            tv_order_type_appstatus_content.setText("已安装此任务");
            isHasInstallApp = true;
            btn_join_task.setText("启动任务");
            iTypeSubmit = 1;
        }
    }

    //开始监听进度
    private void startCheckProgress(long downloadId) {
        Observable
                .interval(1, 10, TimeUnit.MILLISECONDS, Schedulers.io())//无限轮询,准备查询进度,在io线程执行
                .filter(times -> DownloadAppManager.initDownLoadManager(actContext).mDownloadBinder != null)
                .map(i -> DownloadAppManager.initDownLoadManager(actContext).mDownloadBinder.getProgress(downloadId))//获得下载进度
                .takeUntil(progress -> progress >= 100)//返回true就停止了,当进度>=100就是下载完成了
                .distinct()//去重复
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressObserver());
    }


    //观察者
    private class ProgressObserver implements Observer<Integer> {

        @Override
        public void onSubscribe(Disposable d) {
            mDisposable = d;
        }

        @Override
        public void onNext(Integer progress) {
            setCustomLoadingDialogProgressValue(progress);
        }

        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
            setShowAndHideCustomLoadingProgress(false);
            ToastUtil.showShort(actContext,"监控下载进度失败！");

        }

        @Override
        public void onComplete() {
            setCustomLoadingDialogProgressValue(100);
        }
    }

    //=============================开始启动自动任务============================
    @Override
    public void getTimerOrderdMyBroadcastReceiver(String action) {
        KLog.e("----------getTimerOrderdMyBroadcastReceiver-----------:" + action);
        if ("android.myapp.timer.orders.auto.start".equals(action)) {
            //结束本页面
            finish();
        }
    }
}
